#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
找出 eDep_700.0MeV.csv 中的峰(peak)位置
"""

import pathlib as pl

import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import find_peaks

_CWD = pl.Path(__file__).parent
_OUT_DIR = _CWD / "out"
_POST_DIR = _CWD / "post"
_CSV_FILE = _OUT_DIR / "eDep_700.0MeV.csv"
_SAVE_FIG = "eDep_peaks_ann.png"  # 如需保存，设为 None 则不保存

# ---------- 1. 读数据 ----------
iz, mean_edep = [], []
with open(_CSV_FILE, "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        _, _, iz_, sumv, _, n = line.split(",")
        iz.append(int(iz_))
        mean_edep.append(float(sumv) / int(n))
iz = np.array(iz)
mean_edep = np.array(mean_edep)

# ---------- 2. 寻峰 ----------
h_min, h_max = mean_edep.min(), mean_edep.max()
peaks, _ = find_peaks(mean_edep, height=h_min + 0.05 * (h_max - h_min), distance=3)

# ---------- 3. 画图 ----------
plt.figure(figsize=(8, 4))
plt.plot(iz, mean_edep, lw=1.2, color="C0", label="Mean energy deposit")
plt.scatter(iz[peaks], mean_edep[peaks], color="r", zorder=5)

# 在峰顶旁边标出数值
for p in peaks:
    plt.annotate(
        f"{iz[p]}\n{mean_edep[p]:.0f} MeV",
        xy=(iz[p], mean_edep[p]),
        xytext=(5, 10),
        textcoords="offset points",
        color="red",
        fontsize=8,
        ha="left",
        va="bottom",
        arrowprops=dict(arrowstyle="->", color="red", lw=0.8),
    )

plt.xlabel("iZ")
plt.ylabel("Energy deposit / MeV")
plt.title("eDep_700.0MeV – peak positions & values")
plt.tight_layout()

if _SAVE_FIG:
    plt.savefig(_SAVE_FIG, dpi=200)
    print(f"Saved annotated figure -> {_SAVE_FIG}")
plt.show()
